package com.ai.service.impl;

import com.ai.entity.dto.CallAndPatient;
import com.ai.exception.AiException;
import com.ai.mapper.PatientMapper;
import com.ai.service.AiService;
import com.ai.service.CallService;
import com.ai.util.OtherUtil;
import com.ai.util.ReadOrWriteFileUtil;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CallServiceImpl implements CallService {


    @Resource
    private PatientMapper patientMapper;

    @Resource
    private AiService aiService;

    @Resource
    private ThreadPoolTaskExecutor threadPool;


    @Override
    public void exec(String itemName) {
        singleA(itemName);
        System.out.println("==============A步骤已完成=================");
        singleB(itemName);
        System.out.println("==============B步骤已完成=================");
        singleC(itemName);
        System.out.println("==============C步骤已完成=================");
    }

    @Override
    public void singleA(String itemName) {
        System.out.println("============================================================");
        System.out.println("========================singleA开始执行=======================");
        System.out.println("============================================================");

        List<CallAndPatient> patients = patientMapper.findCallAndPatientByName(itemName);
        if (CollectionUtils.isEmpty(patients)) {
            throw new AiException("没有找到该项目");
        }
        List<CallAndPatient> filterPatients = patients.stream()
                .filter(patient -> !Objects.isNull(patient.getEmpiId()))
                .collect(Collectors.toList());
        CountDownLatch latch = new CountDownLatch(filterPatients.size());
        for (CallAndPatient filterPatient : filterPatients) {
            threadPool.execute(() -> {
                String result = aiService.modelA(filterPatient);
                ReadOrWriteFileUtil.syncWriteTxt("A", filterPatient.getName(), result);
                latch.countDown();
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new AiException("A线程中断");
        }
        System.out.println("============================================================");
        System.out.println("========================singleA执行完成=======================");
        System.out.println("============================================================");
    }

    /**
     * 生成的文件过大需要重复去重直到文件大小
     *
     * @param itemName
     */
    @Override
    public void singleB(String itemName) {
        System.out.println("============================================================");
        System.out.println("========================singleB开始执行=======================");
        System.out.println("============================================================");
        //todo 拆分数据后需处理要梳理一下，去单个A拆分多个A+，去多个A+文件写入B+，取多个B+文件递归缩小文件大小至16k以下
        List<String> divideResult = OtherUtil.divideFile("A", itemName, "B");
        CountDownLatch latch = new CountDownLatch(divideResult.size());
        for (String fileName : divideResult) {
            String content = ReadOrWriteFileUtil.readTxt("B", fileName);
            threadPool.execute(() -> {
                CallAndPatient callAndPatient = new CallAndPatient();
                callAndPatient.setName(itemName);
                callAndPatient.setTransText(content);
                String result = aiService.modelB(callAndPatient);
                ReadOrWriteFileUtil.syncWriteTxt("C", itemName, result);
                latch.countDown();
            });
        }
//        List<String> resultList = ReadOrWriteFileUtil.readTxtLines("A", itemName);
//        List<String> strings = divide(resultList);
//        for (int i = 0; i < strings.size(); i++) {
//            int finalI = i;
//            threadPool.execute(() -> {
//                ReadOrWriteFileUtil.writeTxt("B", itemName + finalI, strings.get(finalI));
//                CallAndPatient callAndPatient = new CallAndPatient();
//                callAndPatient.setName(itemName);
//                callAndPatient.setTransText(strings.get(finalI));
//                String result = aiService.modelB(callAndPatient);
//                ReadOrWriteFileUtil.writeTxt("C", itemName, result);
//                latch.countDown();
//            });
//        }
        try {




            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new AiException("B线程中断");
        }
        System.out.println("============================================================");
        System.out.println("========================singleB执行完成=======================");
        System.out.println("============================================================");
    }

    private List<String> divide(List<String> resultList) {
        List<String> modelBText = new ArrayList<>();
        StringBuffer after = new StringBuffer();
        StringBuffer before = new StringBuffer();
        for (String s : resultList) {
            before.append(s);
            if (before.length() > 1000) {
                modelBText.add(after.toString());
                before = new StringBuffer();
                after = new StringBuffer();
                continue;
            }
            after.append(s);
        }
        return modelBText;
    }

    @Override
    public void singleC(String itemName) {
        System.out.println("============================================================");
        System.out.println("========================singleC开始执行=======================");
        System.out.println("============================================================");
        String c = ReadOrWriteFileUtil.readTxt("C", itemName);
        CallAndPatient callAndPatient = new CallAndPatient();
        callAndPatient.setName(itemName);
        callAndPatient.setTransText(c);
        String s = aiService.modelC(callAndPatient);
        ReadOrWriteFileUtil.syncWriteTxt("D", itemName, s);
        System.out.println("============================================================");
        System.out.println("========================singleC执行完成=======================");
        System.out.println("============================================================");
    }

    @Override
    public void singleB1(String itemName) {
        System.out.println("============================================================");
        System.out.println("========================singleB1开始执行=======================");
        System.out.println("============================================================");
        List<String> divideResult = OtherUtil.divideFile("C", itemName, "C1");
        ReadOrWriteFileUtil.deleteFile("C", itemName);
        for (String fileName : divideResult) {
            String content = ReadOrWriteFileUtil.readTxt("C1", fileName);
            CallAndPatient callAndPatient = new CallAndPatient();
            callAndPatient.setName(itemName);
            callAndPatient.setTransText(content);
            String result = aiService.modelB(callAndPatient);
            ReadOrWriteFileUtil.syncWriteTxt("C", itemName, result);
        }
        ReadOrWriteFileUtil.deleteLikeFile("C1", itemName);
        System.out.println("============================================================");
        System.out.println("========================singleB1执行完成=======================");
        System.out.println("============================================================");
    }
}
